<template>
  <div>
    <el-card class="search-card table_form_wrap">
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="100px"
        @submit.native.prevent
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="分类" prop="categoryPath">
              <el-input
                v-model.trim="searchForm.categoryPath"
                placeholder="分类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SPU编码" prop="spuNo">
              <el-input v-model.trim="searchForm.spuNo" placeholder="SPU编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model.trim="searchForm.productName"
                placeholder="商品名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="商品品牌" prop="brandName">
              <el-input
                v-model.trim="searchForm.brandName"
                placeholder="商品品牌"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品类型" prop="productType">
              <el-select
                class="el-select-wrap"
                clearable
                v-model="searchForm.productType"
                placeholder="请选择商品类型"
              >
                <el-option
                  v-for="item in productTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人" prop="createOper">
              <user-select ref="userSelect" v-model="searchForm.createOper" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="完善状态" prop="queryType">
              <el-select
                class="el-select-wrap"
                v-model="searchForm.queryType"
                placeholder="请选择完善状态"
              >
                <el-option
                  v-for="item in queryTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch(1)"
            >查询</el-button
          >
          <span style="margin: 0 2px">&nbsp;</span>
          <el-button icon="el-icon-reset" @click="handleReset('searchForm')"
            >重置</el-button
          >
        </el-row>
      </el-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="480"
        :actionRender="renderTableBtnAction"
        :selectionChange="handleSelectionChange"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button v-if="canOpeState" type="primary" size="mini" icon="el-icon-plus" @click="handleAddSku"
            >新增SKU</el-button
          >
          <el-button
            v-if="showBtn('批量提交')"
            :loading="btnLoading.batchSubmit"
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            :disabled="tableInfo.selection.length == 0"
            @click="handleBatchSubmit"
            >批量提交</el-button
          >
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import BasicTable from '@/components/BasicTable';
import UserSelect from '@/components/commodity/UserRemoteSelect'
// import { handleOpenNewPage, isResponseSuccessState } from '@/utils/bizUtils';
import { isResponseSuccessState } from '@/utils/bizUtils';
import { PRODUCT_TYPES, PIC_STATUS, initPerfectColumns } from '../constants';
import { ACCESS_SKU_STATE_OPTIONS } from '@/constants/commodity';
import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';
import { getCanOpeState } from '@/utils/getUtils';
export default {
  components: {
    BasicTable,
    UserSelect
  },
  data () {
    return {
      tableInfo: {
        list: [],
        columns: initPerfectColumns(this),
        loading: false,
        selection: []
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      searchForm: {
        queryType: '5',
        categoryPath: '',
        spuNo: '',
        productName: '',
        brandName: '',
        productType: '',
        picStateInfo: '',
        createOper: ''
      },
      productTypes: PRODUCT_TYPES,
      picStateList: PIC_STATUS,
      queryTypeOptions: ACCESS_SKU_STATE_OPTIONS,
      // 未完善列表
      getPreparingList: {
        url: '/sysback/product/addSku/stateInfo/getProductAddStateList', // 接口地址
        type: 'post' // 接口请求类型
      },
      batchCreateProductAddSkuRecordInfo: { // 提交接口
        url: '/sysback/product/addSku/recordInfo/batchCreateProductAddSkuRecordInfo',
        type: 'post'
      },
      btnLoading: {
        batchSubmit: false
      },
      canOpeState: true, // 页面可操作状态
    };
  },
  created () {
    this.setCanOpeState()
    if (sessionStorage.getItem('search_params_sku')) {
      this.getSearchParams()
    }
    this.handleSearch()
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const deleteBtn = <el-button
        type="text"
        onClick={() => this.handleToDelete(row)}
      >删除</el-button>;
      if (this.showBtn('删除')) {
        return <div class="table-action">{deleteBtn}</div>;
      }
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 删除
    handleToDelete (row) {
      this.$confirm('删除后将把该商品的所有完善信息删除，您确认吗？', '删除', {
        type: 'warning',
      }).then(() => {
        sessionStorage.setItem('buttonId', getBtnsId('删除'));
        this.deleteRecord(row.productUuid, row.spuNo);
      }).catch(() => {});
    },
    // 删除单据
    async deleteRecord (uuid, spuNo) {
      try {
        const url = `/sysback/product/addSku/stateInfo/deleteByProductuuid?uuid=${uuid}&spuNo=${spuNo}`
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, 'post');
        this.tableInfo.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('删除成功');
          this.handleSearch();
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 获取待完善spu列表数据
    async queryTableDataAction (data) {
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableInfo.loading = true;
      const { retStatus, retData } = await ApiRequest(this.getPreparingList.url, this.getPreparingList.type, data, false)
      this.tableInfo.loading = false;
      if (isResponseSuccessState(retStatus)) {
        const { results, totalNum } = retData;
        this.pagination.totalNum = totalNum;
        this.tableInfo.list = results;
      }
    },
    // 回显历史查询条件
    getSearchParams () {
      const {
        queryType,
        categoryPath,
        spuNo,
        productName,
        brandName,
        productType,
        picStateInfo,
        nowPage,
        pageShow
      } = JSON.parse(sessionStorage.getItem('search_params_sku'))
      this.searchForm = {
        queryType,
        categoryPath,
        spuNo,
        productName,
        brandName,
        productType,
        picStateInfo,
      }
      this.pagination = {
        nowPage,
        pageShow,
        totalNum: 0
      }
    },
    // 查询表格数据
    handleSearch (initPageNum) {
      if (initPageNum) {
        this.pagination.nowPage = initPageNum;
      }
      const { nowPage, pageShow } = this.pagination;
      const param = {
        nowPage,
        pageShow,
        ...this.searchForm,
        groupFlag: '1' // 是否是集团总部 0:不是 1:是
      };
      sessionStorage.setItem('search_params_sku', JSON.stringify(param))
      this.queryTableDataAction(param);
    },
    // 重置表单
    handleReset (formName) {
      this.$refs.userSelect.resetSelectVal();
      this.$refs[formName].resetFields();
      this.searchForm = {
        queryType: '5',
        categoryPath: '',
        spuNo: '',
        productName: '',
        brandName: '',
        productType: '',
        picStateInfo: '',
        createOper: ''
      }
      this.handleSearch(1);
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.handleSearch();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.handleSearch(1);
    },
    // 新增sku
    handleAddSku () {
      this.$router.push({ name: 'skuAdd' });
    },
    // 链接子页面跳转
    handleLinkJump (row, pageRouterName, state) {
      const notJumpStateList = ['AUDITING', 'OK'];
      if (pageRouterName == 'skuPriceInfo' && row.supplyPriceAddState == 'INIT') {
        return this.$message.warning('请先完善供货信息');
      }
      // 路由name集合
      if (!notJumpStateList.includes(state)) {
        /* handleOpenNewPage(this, {
          name: pageRouterName,
          query: {
            productUuid: row.productUuid,
            isPurchaseMultiUnit: row.isPurchaseMultiUnit
          }
        }); */
        if (pageRouterName == 'skuPriceInfo') {
          return this.$router.push({
            name: pageRouterName,
            query: {
              productUuid: row.productUuid,
              addStateStr: row.salePriceAddStateStr
            }
          })
        }
        this.$router.push({
          name: pageRouterName,
          query: {
            productUuid: row.productUuid,
            isPurchaseMultiUnit: row.isPurchaseMultiUnit
          }
        })
      }
    },
    // 格式化link type
    formatLinkType (type) {
      let linkType = 'info';
      switch (type) {
        case 'INIT': // 待完善
          linkType = 'primary';
          break;
        case 'ADDING': // 完善中
          linkType = 'primary';
          break;
        case 'FAIL': // 审核驳回
          linkType = 'danger';
          break;
        case 'ADD_OK': // 已完善
          linkType = 'success';
          break;
        case 'AUDITING': // 审核中
          linkType = 'info';
          break;
        case 'OK': // 已完成
          linkType = 'info';
          break;
      }
      return linkType;
    },
    // 批量提交
    handleBatchSubmit () {
      const canSubmit = judgeAuthDepartmentFn(this.tableInfo.selection); // 验归属部门方法
      if (!canSubmit) {
        return false;
      }
      const { url, type } = this.batchCreateProductAddSkuRecordInfo;
      const data = this.tableInfo.selection.map(row => row.productUuid);
      const title = '批量操作';
      const content = '确定批量提交吗？';
      this.btnLoading.batchSubmit = true;
      this.$confirm(content, title, {
        type: 'warning'
      }).then(async () => {
        sessionStorage.setItem('buttonId', getBtnsId('批量提交'));
        const res = await ApiRequest(url, type, data);
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('批量提交成功');
          this.handleSearch();
        }
      }).catch().finally(() => {
        this.btnLoading.batchSubmit = false;
      })
    }
  }
};
</script>
<style lang="less" scoped>
.el-select-wrap {
  width: 100%;
}
</style>
